package com.bocai.eelly.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.SparseArray;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.bocai.eelly.R;
import com.bocai.eelly.adapter.FindHuoDaiAdp;
import com.bocai.eelly.bean.FindHuodaiListBean;
import com.bocai.eelly.bean.PopBean;
import com.bocai.eelly.bean.PortBean;
import com.bocai.eelly.common.BaseActivity;
import com.bocai.eelly.common.Loading;
import com.bocai.eelly.common.ToolbarHelper;
import com.bocai.eelly.net.ApiManage;
import com.bocai.eelly.utils.DeviceUtil;
import com.bocai.eelly.utils.L;
import com.bocai.eelly.utils.PopUtil;
import com.bocai.eelly.utils.T;
import com.bocai.eelly.utils.Utils;
import com.bocai.eelly.views.ExpandTabView;
import com.bocai.eelly.views.XListView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 找货代
 */
public class FindHuoDaiListActivity extends BaseActivity implements OnClickListener, XListView.IXListViewListener, AdapterView.OnItemClickListener {

    @Bind(R.id.lv_find_new_products)
    XListView lvFindNewProducts;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.search)
    RelativeLayout search;
    @Bind(R.id.toggleBtn)
    ToggleButton toggleBtn;
    @Bind(R.id.ll_select_stock)
    LinearLayout llSelectStock;
    private ArrayList<String> groups = new ArrayList<String>();
    private SparseArray<LinkedList<String>> children = new SparseArray<LinkedList<String>>();
    private int page = 1;
    private FindHuoDaiAdp findHuoDaiAdp;
    private List<FindHuodaiListBean.DataEntity> dataEntities = new ArrayList<>();
    private PopUtil pu;
    private ToggleButton selectedButton;
    private ExpandTabView.OnButtonClickListener mOnButtonClickListener;
    private String country="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_huodai_list);
        ButterKnife.bind(this);
        toggleBtn.setText("目的国");
        initView();
        initEvent();
    }

    private void initEvent() {
        llSelectStock.setOnClickListener(this);
        toggleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                String timeline2=Utils.getTimeline();
                String sign2=Utils.md5(timeline2);
                ApiManage.getDestionation(FindHuoDaiListActivity.this, timeline2, sign2, Utils.getUserId(FindHuoDaiListActivity.this, "id"), new Action1<PortBean>() {
                    @Override
                    public void call(PortBean portBean) {
//                        PostHuoDaiActivity.this.portBean=portBean;
                        if (Utils.checkResultCode(portBean.getReturn_code()))
                        {

                            ToggleButton tButton = (ToggleButton) view;

                            if (selectedButton != null && selectedButton != tButton) {
                                selectedButton.setChecked(false);
                            }
                            int width = new DeviceUtil(FindHuoDaiListActivity.this).getWidth();
                            showPopwindow(llSelectStock, setSortList(portBean), width, 20);
                            selectedButton = tButton;
                            if (mOnButtonClickListener != null && tButton.isChecked()) {
                                mOnButtonClickListener.onClick();
                            }

                        }
                    }
                });

            }
        });
        lvFindNewProducts.setXListViewListener(this);
        lvFindNewProducts.setPullLoadEnable(false);
        lvFindNewProducts.setPullRefreshEnable(true);
        lvFindNewProducts.setOnItemClickListener(this);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                startActivity(new Intent(FindHuoDaiListActivity.this, PostHuoDaiActivity.class));
                return false;
            }
        });
        search.setOnClickListener(this);
    }

    private void showPopwindow(View v, ArrayList<PopBean> list, int width, int height) {

        pu = PopUtil.getInstance(this, v,toggleBtn, width, height, list);
        pu.setListener(new PopUtil.OnDatePopClickListener() {
            @Override
            public void onClick(PopUtil pu, PopBean date) {
                toggleBtn.setText(date.getName());
                country=date.getName();
                page = 1;
                dataEntities.clear();
                lvFindNewProducts.setPullLoadEnable(false);
                getHuodais();
                pu.dismiss();
            }
        });
        pu.show();
    }

    private void initView() {
        getHuodais();
        ToolbarHelper.setup(this, R.string.str_title_find_huodai, R.mipmap.ic_back, new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        toolbar.inflateMenu(R.menu.menu_find_accessories);
        findHuoDaiAdp = new FindHuoDaiAdp(this, dataEntities);
        lvFindNewProducts.setAdapter(findHuoDaiAdp);
    }

    private void getHuodais() {
        String timeline = Utils.getTimeline();
        String sign = Utils.md5(timeline);
        getTestApi().findHuodai(timeline, sign, Utils.getUserId(this, "id"), page, Utils.PAGESIZE, "",country)
                .compose(this.<FindHuodaiListBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<FindHuodaiListBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        lvFindNewProducts.stopRefresh();
                        Loading.dismiss();
                        L.d(e.toString());
                        T.showShort(FindHuoDaiListActivity.this, R.string.net_error);
                    }

                    @Override
                    public void onNext(FindHuodaiListBean findHuodaiListBean) {
                        lvFindNewProducts.stopRefresh();
                        Loading.dismiss();
                        L.d(findHuodaiListBean.getMsg());
                        if (Utils.checkResultCode(findHuodaiListBean.getReturn_code())) {
                            dataEntities.addAll(findHuodaiListBean.getData());
                            findHuoDaiAdp.notifyDataSetChanged();
                            if (findHuodaiListBean.getData().size() < Utils.PAGESIZE) {
                                lvFindNewProducts.setPullLoadEnable(false);
                            }else
                            {
                                lvFindNewProducts.setPullLoadEnable(true);

                            }
                        } else {
                            T.showLong(FindHuoDaiListActivity.this, findHuodaiListBean.getMsg());
                        }
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search:
                startActivity(new Intent(this, SearchHuodaiActivity.class));
                break;
            case R.id.ll_select_stock:


                String timeline2=Utils.getTimeline();
                String sign2=Utils.md5(timeline2);
                ApiManage.getDestionation(this, timeline2, sign2, Utils.getUserId(this, "id"), new Action1<PortBean>() {
                    @Override
                    public void call(PortBean portBean) {
//                        PostHuoDaiActivity.this.portBean=portBean;
                        if (Utils.checkResultCode(portBean.getReturn_code()))
                        {

                            int width = new DeviceUtil(FindHuoDaiListActivity.this).getWidth();
                            showPopwindow(llSelectStock, setSortList(portBean), width, 20);

                        }
                    }
                });

                break;
        }
    }


    private ArrayList<PopBean> setSortList(PortBean portBean) {
        ArrayList list = new ArrayList<>();
        for (int i = 0; i < portBean.getData().size(); i++) {
            PopBean popBean = new PopBean();
            popBean.setId(i+"");
            popBean.setName(portBean.getData().get(i).getCountry());

            list.add(i, popBean);
        }

        return list;
    }

    @Override
    public void onRefresh() {
        page = 1;
        dataEntities.clear();
        lvFindNewProducts.setPullLoadEnable(false);
        getHuodais();
    }

    @Override
    public void onLoadMore() {
        page++;
        getHuodais();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}
